<template>
  <div class="all_bg">
    <!-- 右侧固定栏 -->
  	<w-right-float></w-right-float>
    <!-- 左侧导航栏 -->
  	<div class="left-fix" id="leftFix" v-show="showIs">
      <ul class="left-fix-nav" id="leftfixnav">
        <li class="fix-li">导航</li>
        <li v-for="(item, index) in sexList" :key="index" class="main-nav">
          <ul class="clearfix child">
            <li v-for="(val, key) in item.tradeFloor" :key="key" class="clearfix sex-style" @click.stop="onJump($event.target, key)" @mouseover="onMouseEnter($event.target, key)" @mouseout="onMouseLeave($event.target, key)">
              {{val.floorName.substring(0, 4)}}
            </li>
          </ul>
        </li>
      </ul>
    </div>
  	<div class="content index-content">
      <!-- 搜索区域 -->
      <w-index-header @on-index="getIndexInfo" @on-channel="getChannel"></w-index-header>
      <!-- 主导航区域 -->
      <w-banner-bar :mainNavList="mainNavList" @on-channel="getChannel" @index-number="indexNumber" :return-index="returnIndex"></w-banner-bar>
      <!-- 轮播图 -->
      <div class="content1" v-if="!bannerList && !indexFloorData || !bannerList.length && !indexFloorData.length || bannerList.length <= 0 && indexFloorData.length <= 0"></div>
      <div class="login-container clearfix" v-if="!$store.getters.token && showIf && !$route.query.cIndex && bannerList.length">
        <div class="login-box">
          <w-form-validate @on-validate="onValid">
            <div class="login-wrap fr">
              <div class="main-pad">
                <div class="login-img">
                  <span>
                    <img src="../assets/logo.png" alt="">
                  </span>
                </div>
                <p class="welcome">Hi!你好</p>
                <div class="input-box clearfix phone">
                  <w-input class="fl login-input index-login" type="text" v-model="username" holder="会员名/手机号" rule="isEmpty|isMobile" error="请输入手机号码|亲，请输入正确的手机号码|亲，该手机号码未注册" :maxlength="11"></w-input>
                </div> 
                <div class="input-box clearfix password">
                  <w-input class="fl login-input index-login" type="password" v-model="password" holder="密码" rule="isEmpty|isPassword" error="请输入登录密码|亲，您的密码不正确" :maxlength="16"></w-input>
                </div>    
                <w-button type="main">登录</w-button>
              </div>
            </div>
          </w-form-validate>
        </div>
      </div>
      <div class="login-container clearfix" v-if="$store.getters.token && showIf && !$route.query.cIndex && bannerList.length">
        <div class="login-box">
          <w-form-validate @on-validate="onValid">
            <div class="login-wrap fr">
              <div class="main-pad">
                <div class="login-img logined-img">
                  <span>
                    <img src="../assets/photo.png" v-if="!userHeadImg" alt="">
                    <img :src="userHeadImg" v-else alt="">
                  </span>
                </div>
                <p class="customer">{{$store.getters.nickName}}</p>
                <div class="customer-box">
                    <div class="customer-info" @click="goToMy()">
                        <span>待发货</span>
                        <span v-text="orderList.WaitDelivOrderCount"></span>
                    </div>
                    <div class="customer-info" @click="goToMy()">
                        <span>待收货 </span>
                        <span v-text="orderList.waitGetorderCount"></span>
                    </div>
                    <div class="customer-info" @click="goToMy()">
                        <span>待付款</span>
                        <span v-text="orderList.waitPayCount"></span>
                    </div>
                    <div class="customer-info" @click="goToMy()">
                        <span>待评价</span>
                        <span v-text="orderList.waitEvaorderCount"></span>
                    </div>
                </div>
              </div>
            </div>
          </w-form-validate>
        </div>
      </div>
      <w-banner @shade="showShade" :lists="bannerList" :height="420" v-if="bannerList.length > 0" @on-channel="getChannel"></w-banner>
      <!-- 视频播放组件 -->
      <w-video @shade="showShade" v-if="showIf && !this.$route.query.cIndex"></w-video>
      <!-- 楼层数据 -->
      <w-index-floor :floor="indexFloorData" :sex-list="sexList" @on-channel="getChannel"></w-index-floor>
    </div>
    <!-- 遮罩层 -->
    <div class="shade" v-show="showVideoShade"></div>
  </div>
</template>

<script>
  import { apiOrderStatusCount, apiIndexFloor, apiLeftNav, apiBanner, apiChannelFloor, apiOrderAll, apiTrade, apiFavoriteStore, apiLogin } from '../common/api'
  import { mapActions, mapGetters, mapMutations } from 'vuex'
  import { wScroll, session } from '../common/util'
  // import { apiLogin, apiOrderAll } from 'js/api'
  import { USER_ROLE } from '../common/config'
  export default {
    data() {
      return {
        indexFloorData: [], // 楼层
        bannerList: [], // banner列表
        mainNavList: [], // 主导航数据
        sexList: [],
        tradeList: [],
        isTradePop: session.get('isTradePop'),
        currentFloorIndex: 0,
        aTradeColor: [], // 左侧固定栏颜色
        showIs: true,
        username: '',
        password: '',
        localIp: '',
        showVideoShade: '',
        orderList: [],
        showIf: true,
        returnIndex: 0
      }
    },
    created() {
      // 如果当前是1，则关闭浏览器
      if (this.$route.query.isOpen == 1) {
        window.close()
        return
      }
      this.fetchTrade()
      this.fetchLeftNav()
      // 消息接口，如果没有登录则不需要请求
      if (this.token) {
        apiOrderAll(this.token, 1, '', '', 3).then(data => {
          this.updateMsgList(data.orderFormList)
        })
        this.fetchOrderStatusCount(this.token)
      }
      if (this.$route.params.chId && this.$route.params.chId != undefined) {
        this.fetchIndexFloor('', this.$route.params.chId)
      } else {
        this.fetchIndexFloor(this.industry, '')
      }
      this.localIp = returnCitySN['cip']
      this.fetchMobile()
      this.returnIndex = this.$route.query.cIndex
    },
    mounted() {
      $('#leftfixnav').css('opacity', 0)
    },
    methods: {
      ...mapMutations(['updateIndexFloorTop', 'updateIndexFloorIndex', 'updateMsgList', 'updateTradeList', 'updateUserInfoIndustry']),
      // 跳转我的订单
      goToMy() {
        window.open('/my/order')
      },
      // 展示遮罩层
      showShade(flag) {
        this.showVideoShade = flag
      },
      // 点击左侧行业分类切换
      chooseSex(index, id) {
        this.updateUserInfoIndustry(id)
        this.fetchIndexFloor(id, '')
        this.fetchBanner(id)
      },
      // 行业选择请求
      fetchTrade() {
        apiTrade().then(data => {
          this.tradeList = data.TradeList
          this.updateTradeList(this.tradeList || [])
          session.set('peopleList', data.TradeList)
        })
      },
      fetchOrderStatusCount(token) {
        apiOrderStatusCount(token).then(data => {
          this.orderList = data
        })
      },
      // 首页楼层请求
      fetchIndexFloor(id, chId) {
        if (chId) {
          // 请求频道楼层
          this.fetchChannelFloor(chId)
        } else {
          this.indexFloorData = []
           // 请求banner
          this.fetchBanner(id)
          // 请求首页楼层
          apiIndexFloor(id, this.token).then(data => {
            this.showIs = true
            // 保存楼层数据
            this.indexFloorData = data.GoodsFloor || []
            // 保存楼层颜色
            this.indexFloorData.forEach(floor => {
              // 若显示楼层标题信息，则展示
              if (floor.isViewName == '1') {
                this.aTradeColor.push(floor.gf_css)
              }
            })
            // // 保存楼层轮播图
            // const aResult1 = data.GoodsFloor || []
            // // const aResult2 = []
            // aResult1.forEach(banner => {
            //   if (banner.wide_template == 'new_product') {
            //     this.bannerList1.push(banner.wideGoodsList[2].right.goodsList)
            //   }
            // })
            this.onCollect()
            this.$store.commit('updateChannelLength', data.GoodsFloor.length)
            // 初始化颜色
            $('.sex-style').eq(this.currentFloorIndex).css('background', `#${this.aTradeColor[this.currentFloorIndex]}`)
            // 计算楼层位置，以及开始执行滚动
            this._getIndexFloorTop()
            wScroll(top => {
              const cur = this._getScorllIndex(top)
              this.currentFloorIndex = cur
              $('.sex-style').eq(this.currentFloorIndex).css('background', `#${this.aTradeColor[this.currentFloorIndex]}`).siblings().css('background', `#777`)
              if (top > 800) {
                $('#leftfixnav').css('opacity', 1)
              } else {
                $('#leftfixnav').css('opacity', 0)
              }
            }).mount()
          })
        }
      },
      // 返回首页获取数据
      getIndexInfo(data) {
        this.fetchTrade()
        // this.fetchBanner(this.industry)
        this.fetchLeftNav()
        this.fetchIndexFloor(this.industry, '')
        this.returnIndex = data
      },
       // 首页频道楼层
      fetchChannelFloor(id) {
        this.indexFloorData = []
        window.scrollTo(0, 0)
        this.showIs = false
        // 请求频道banner
        this.fetchBanner(id)
        // 请求频道楼层
        apiChannelFloor(id, this.token).then(data => {
          this.indexFloorData = data.ChannelFloor
          this.$store.commit('updateChannelLength', data.ChannelFloor.length)
          this.onCollect()
        })
      },
      // 首页Banner
      fetchBanner(id) {
        this.bannerList = [] // 清空，防止脏数据
        apiBanner(id).then(data => {
          const aResult = data.banners || []
          this.bannerList = aResult.map((item, index) => {
            return {
              // link: `${item.ad_url.replace('#/', '')}`,
              image: `${item.path}`,
              type: `${item.type}`,
              value: `${item.value}`
            }
          })
        })
      },
      // 左侧导航请求
      fetchLeftNav() {
        apiLeftNav(this.industry).then(data => {
          this.sexList = data.tradeList
          let tradeFloor = []
          if (this.sexList && this.sexList.length) {
            this.sexList.forEach((list, listIndex) => {
              list.tradeFloor.forEach(v => {
                // 过滤不显示的楼层
                if (v.isViewName == '1') {
                  tradeFloor.push(v)
                }
              })
              this.sexList[listIndex].tradeFloor = tradeFloor
            })
          }
          this.updateTradeList(data.tradeList || [])
          setTimeout(() => {
            if (document.body.offsetWidth < 1340) {
              $('#leftfixnav').addClass('lefts-navs').removeClass('left-fix-nav')
            } else {
              $('#leftfixnav').addClass('left-fix-nav').removeClass('lefts-navs')
            }
          }, 1000)
        })
      },
      // 获取频道楼层
      getChannel(id) {
        this.$router.push(`/index/${id}`) // 标识为channel类型
        if (id) {
          this.fetchChannelFloor(id)
        } else {
          this.fetchIndexFloor(this.industry)
        }
      },
      // 获取子组件传过来的频道id
      indexNumber(id) {
        this.returnIndex = id
      },
      // // 选择行业请求
      // selectCompany(id) {
      //   this.isTradePop = true
      //   session.set('isTradePop', true)
      //   // 更新行业信息
      //   this.$store.commit('updateUserInfoIndustry', id)
      //   // 更新频道导航栏
      //   this.$store.dispatch('apiIndexNavList', id)
      //   this.fetchIndexFloor(id, '')
      // },
      // 获取当前所有楼层，并且计算他的Top位置
      _getIndexFloorTop() {
        setTimeout(() => {
          let aJumpItem = document.querySelectorAll('.jump-content')
          aJumpItem = Array.from(aJumpItem)
          let aJumpPos = []
          // let height = $('.scroll-seach').height() + 14
          // console.log(height)
          aJumpItem && aJumpItem.forEach(item => {
            let offsetTop = item.offsetTop - 51
            $(item).attr('data-top', offsetTop)
            aJumpPos.push(offsetTop)
          })
          this.updateIndexFloorTop(aJumpPos)
        }, 14)
      },
      // 滚动时，查询当前位置对应的索引
      _getScorllIndex(top) {
        let current = 0
        this.aJumpPosition.forEach((num, index) => {
          if (top >= (num - 5)) {
            current = index
          }
        })
        return current
      },
      // 行业选择跳转
      onJump(el, index) {
        this.$nextTick(() => {
          this.currentFloorIndex = index
          $(el).css('background', `#${this.aTradeColor[this.currentFloorIndex]}`).siblings().css('background', `#777`)
          document.body.scrollTop = this.aJumpPosition[index]
          document.documentElement.scrollTop = this.aJumpPosition[index]
        })
      },
      onMouseEnter(el, index) {
        if (index != this.currentFloorIndex) {
          $(el).css('background', `#${this.aTradeColor[index]}`)
        }
      },
      onMouseLeave(el, index) {
        if (index != this.currentFloorIndex) {
          $(el).css('background', `#777`)
        }
      },
      // 添加首页收藏事件
      onCollect() {
        this.$nextTick(() => {
          const _this = this
          const allCollect = $('.JCollect')
          allCollect.on('click', function() {
            const storeId = $(this).data('id') + ''
            const $collectIcon = $(this).find('.jCollectIcon').eq(0)
            apiFavoriteStore(storeId, _this.token).then(data => {
              if (data.deleteStatus == 1) {
                _this.$toast('取消收藏', () => {
                  $collectIcon.toggleClass('collectino-imgs')
                })
                return
              }
              _this.$toast('收藏成功', () => {
                $collectIcon.toggleClass('collectino-imgs')
              })
            })
          })
        })
      },
      ...mapActions(['fetchCartCount']),
      ...mapMutations(['updateMsgList']),
      fetchMobile() { // 记住手机号
        this.username = (this.mobile || sessionStorage.getItem('mobile'))
      },
      // 登录
      onValid() {
        apiLogin(this.username, md5(this.password), this.localIp || '').then((data) => {
          if (data.code == '1004') {
            this.$toast('亲，该手机号码未注册', () => {
              this.$router.push('./register')
              // 清空当前页的用户，密码
              this.username = ''
              this.password = ''
            })
          } else if (data.code == '200') {
            // 保存当前的用户所有数据，包括access_to，头像，昵称等
            this.$store.commit('updateUserInfo', data.data)
            sessionStorage.setItem('mobile', this.username)
            // 当前是采购商，BUYER
            if (data.data.userRole != USER_ROLE.CUSTOMER) {
              // 登录成功后，获取导航的数据
              this.fetchCartCount(this.token)
              this.fetchOrderStatusCount(this.token)
              apiOrderAll(this.token, 1, '', '', 3).then(data => {
                this.updateMsgList(data.orderFormList)
              })
              // 根据路由跳转页面
              if (this.$route.query.redirect) {
                this.$router.push(this.$route.query.redirect)
              } else {
                // 成功登陆，跳转首页
                this.$router.push('/')
              }
            // 判断是否是销售，如果是CUSTOMER则直接去聊天页面
            } else if (data.data.userRole == USER_ROLE.CUSTOMER) {
              this.$router.push('/chat')
            }
          } else if (data.code == '1003') {
            this.$toast('亲，您的密码不正确')
          }
        })
      }
    },
    computed: {
      ...mapGetters(['industry', 'token', 'aJumpPosition', 'mobile', 'nickName', 'userHeadImg'])
    },
    destroyed() {
      wScroll().unmount()
    }
  }
</script>
<style lang="scss">
  .index-content{
    .banner-img {
        width: 161px !important;
        height: 146px !important;
        background: url('../assets/logo.png') no-repeat center;
        background-size: auto;
        margin-top: 30px;
        cursor: pointer;
        box-shadow: 1px 4px 10px #888888;
        position: absolute;
        top:0;
    }
    .index-login {
      .error-tip,.rule-tip{
        margin-top:22px !important;
      }
      input{
        height: 22px;
        font-size: 12px;
        // 登录输入框
        &::-webkit-input-placeholder{
          color: #fff;
        }
        &:-moz-placeholder{
          color: #fff;
        }
        &::-moz-placeholder{
          color: #fff;
        }
        &:-ms-input-placeholder{
          color: #fff;
        }
      }
    }
  }
</style>
<style lang="scss" scoped>
  @import '../scss/_var.scss';
  .placeholder input::-webkit-input-placeholder { /* WebKit browsers */ 
    color: #FFFFFF; 
  } 
  .placeholder input::-moz-placeholder { /* Mozilla Firefox 4 to 18 */ 
    color: #FFFFFF;
  } 
  .placeholder input::-moz-placeholder { /* Mozilla Firefox 19+ */ 
    color: #FFFFFF;
  } 
  .placeholder input::-ms-input-placeholder { /* Internet Explorer 10+ */ 
    color: #FFFFFF;
  }
  .all_bg{
    position: relative;
    .content1 {
      background-image: url(../assets/nullIcon/icon_null.png);
      margin: 50px auto auto;
      width: 100%;
      height: 420px;
      background-repeat: no-repeat;
      text-align: center;
      background-size: contain;
      background-position: 50% 50%;
    }
    .login-container{
      width: 100%;
      position: relative;
      z-index: 1;
      .login-box{
        width: 1230px;
        min-width: 1230px;
        position: relative;
        margin: 0 auto;
        .login-wrap {
          width: 220px;
          height: 240px;
          position: absolute;
          right: 0;
          top:20px;
          // margin: 76px 0;
          background: rgba(255,255,255,.8);
          .main-pad{
            padding: 0 41px;
            height: inherit;
            .login-img{
              display: -webkit-flex; /* Safari */
              display: flex;
              justify-content:center;
              margin-top:25px;
              span{
                background:#D1D1D1;
                width:66px;
                height: 66px;
                border-radius:33px;
                display: -webkit-flex; /* Safari */
                display: flex;
                align-items:center;
                justify-content:center;
                img{
                  width:60px;
                  display: inline;
                  height: auto;
                }
              }
            }
            .logined-img{
              span{
                img{
                  width:66px;
                  display: inline;
                  height: 66px;
                  border-radius: 50%;
                }
              }
            }
            .welcome{
              text-align:center;
              margin-top:5px;
              margin-bottom:20px;
              letter-spacing:2px;
            }
            .customer{
              text-align:center;
              margin-top:5px;
              margin-bottom:10px;
              letter-spacing:2px;
              font-size:14px;
              overflow: hidden;
              word-wrap: break-word;
              white-space: pre;
              text-overflow: ellipsis;
            }
            .customer-box{
              padding:10px 20px;
              border-top:1px solid #D3D3D3;
              .customer-info{
                cursor: pointer;
                margin-bottom:10px;
                font-size:14px;
                display: -webkit-flex; /* Safari */
                display: flex;
                justify-content: space-between;
                span:last-child{
                  color:$color-main;
                }
              }
            }
            // background: $color-white;
            .input-box {
              .login-title {
                width: 38px;
                height: 38px;
                border: 1px solid $color-btn-ghost-bd;
                border-right: none;
                img {
                  background: $bg-gray;
                }
              }
              &.phone {
                margin-bottom: 16px;
              }
              &.password {
                margin-bottom: 16px;
              }
              .login-input {
                display: inline-block;
                width: 100%;
                background:#D1D1D1;
              } 
            }
            .main {
              width: 100%;
              font-size: 14px;
              margin-bottom: 30px;
              height: 18px;
            }
          }
        }
      }
    }
    background-color:#f6f6f6;
    .shade {
      position: fixed;
      top: 0;
      bottom: 0;
      width: 100%;
      z-index: 50;
      background-color: rgba(0,0,0,0.6);
      overflow: hidden;
      .content-company {
        margin: 13% auto;
        width: 320px;
        height: 370px;
        border-radius: 8px;
        background-color: #fff;
        p {
          font-size: 30px;
          text-align: center;
          height: 72px;
          line-height: 72px;
          font-size: 20px;
          background-color: #f00384;
          color: #fff;
          margin-bottom: 60px;
          border-radius: 8px 8px 0 0;
        }
        div {
          font-size: 20px;
          text-align: center;
          height: 40px;
          line-height: 40px;
          cursor: pointer;
          margin: 30px auto;
          width: 180px;
          border-radius: 5px;
          &:nth-child(2) {
            background-color: #f9608b;
          }
          &:nth-child(3) {
            background-color: #6088f9;
          }
          &:nth-child(4) {
            background-color: #f9a460;
          }
          color: #fff;
        }
      }
    }
  }
  /*左侧导航栏*/
  .left-fix {
    .left-fix-nav {
      position: fixed;
      top: 30%;
      left: calc(50vw - 615px - 56px);
      z-index: 10;
      color: $color-white;
    }
    .lefts-navs {
      position: fixed;
      top: 20%;
      left: 0;
      z-index: 10;
      color: $color-white;
    }
    .fix-li{
      height: 36px;
      line-height: 36px;
      background-color: #F00385 !important;
      text-align:center;
    }
    .main-nav {
      margin-bottom: 10px;
      background-color: #777777;
      cursor: pointer;
      &.selected {
        background-color: $color-main;
      }
      &:hover {
        background-color:$color-main;
      }
      div {
        width: 36px;
        font-size: 14px;
        text-align: center;
        height: 36px;
        line-height: 36px;
        border-radius: 2px;
      }
      ul {
        li {
          background-color: #777777;
          width: 36px;
          height: 36px;
          font-size: 12px;
          padding: 4px;
          text-align: center;
          // &.selected {
          //   background-color: #38B9D6;
          // }
          // &:hover {
          //   background-color: #38B9D6;
          // }
        }
      }
    }
    .sex-style {
      font-size: 18px;
      cursor: pointer;
      border-bottom: 1px solid #fff;
      &:nth-child(1) {
        border-top: 1px solid #fff;
      }
    }
    .font-sex {
      font-size: 20px;
    }
  }
</style>